﻿#include"List.h";
void LTprint(LTNode* phead)
{
	LTNode* head = phead->next;
	while (head != phead  )
	{
		printf("%d -> ", head->data);
		head = head->next;
	}
	printf("\n");
}

//申请结点
LTNode* LTBuyNode(LTDatatype x)
{
	LTNode* node = (LTNode*)malloc(sizeof(LTNode));
	if (node == NULL)
	{
		perror("node error");
		exit(1);
	}
	node->data = x;
	node->next = node->prev = node; //循环指向自己

	return node;
}

////初始化  
//void  LTInit(LTNode** pphead)
//{
//	//给链表初始化一个哨兵位
//	*pphead = LTBuyNode(0);
//}

//返回值类型的哨兵位
LTNode* LTInit()
{
	LTNode* node = LTBuyNode(-1);
	return node;

}


//插入数据前，链表必须初始化到只有一个头节点的情况, 不改变哨兵位的地址，因此传一级即可
LTNode* LTpushback(LTNode* phead, LTDatatype x)
{
	assert(phead);
	 
	LTNode* node = LTBuyNode(x);

	node->next = phead;
	node->prev = phead->prev;

	phead->prev->next = node;
	phead->prev = node;
}

LTNode* LTpushfront(LTNode* phead, LTDatatype x)
{
	assert(phead);
	
	LTNode* newnode = LTBuyNode(x);
	newnode->prev = phead;
	newnode->next = phead->next;
		
	phead->next->prev = newnode;
	phead->next = newnode;
}

//LTNode* LTpopback(LTNode* phead, LTDatatype x)
//{
//	assert(phead);
//	phead->prev->prev->next = phead;
//	phead->prev = phead->prev->prev;
//}

LTNode* LTpopback(LTNode* phead, LTDatatype x)
{
	assert(phead);
	if (phead->next == phead)
	{
		return NULL;
	}
	else
	{
		LTNode* pcur = phead->prev;
		pcur->prev->next = phead;
		phead->prev = pcur->prev;
		
		//删除pcur 
		free(pcur);
		pcur = NULL;
	}
}
LTNode* LTpopfront(LTNode* phead)
{
	assert(phead || phead->next != phead);

	LTNode* del = phead->next;
	phead->next = del->next; 
	del->next->prev = phead;

	free(del);
	del = NULL;
}

LTNode* LTFind(LTNode* phead, LTDatatype x)
{
	LTNode* pcur = phead->next;
	while (pcur != phead)
	{
		if (pcur->data == x)
			return pcur;
		pcur = pcur->next;
	}
	return NULL;
}

//在指定位置插入数据
LTNode* LTInsert(LTNode* pos, LTDatatype x)
{
	assert(pos);
	
	LTNode* newnode = LTBuyNode(x);
	newnode->prev = pos;
	newnode->next = pos->next;

	pos->next->prev = newnode;
	pos->next = newnode;
}

LTNode* LTErase(LTNode* pos)
{
	assert(pos);

	pos->prev->next = pos->next;
	pos->next->prev = pos->prev;

	free(pos);
	pos = NULL;
}